package com.iretailer.report.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iretailer.report.dto.PageResult;
import com.iretailer.report.dto.QueryOption;
import com.iretailer.report.mapper.CompaniesMapper;
import com.iretailer.report.model.Companies;
import com.iretailer.report.model.Malls;
import com.iretailer.report.model.User;
import com.iretailer.report.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Auther: xjw
 * @Date: 2019/1/24 11:14
 * @Description:
 */
@Service
public class CompanyService extends ServiceImpl<CompaniesMapper, Companies> {

    @Autowired
    private CompaniesMapper companiesMapper;
    @Autowired
    private MallsService mallsService;

    public PageResult<Companies> selectPage(String companyId, String companyName, QueryOption queryOption) {
        Page page = new Page<Companies>(1, Long.MAX_VALUE);
        QueryWrapper<Companies> queryWrapper = new QueryWrapper<>();
        if (companyId != null) {
            //能查看自己的公司
            queryWrapper.eq("id", companyId);
            //查看 自己公司的子公司
            List<String> parentIds = getTreeId(companyId);
            parentIds.add(companyId);
            queryWrapper.or().in("parentId", parentIds);
        }
        if (companyName != null) {
            queryWrapper.like("name", companyName);
        }
        queryOption.judge(page, queryWrapper);
        IPage pageInfo = companiesMapper.selectPage(page, queryWrapper);
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getRecords());
    }


    public List<Companies> selectCompanyInfo(String companyId) {
        QueryWrapper<Companies> queryWrapper = new QueryWrapper<>();
        if (companyId != null) {
            //能查看自己的公司
            queryWrapper.eq("id", companyId);
            //查看 自己公司的子公司
            List<String> parentIds = getTreeId(companyId);
            parentIds.add(companyId);
            queryWrapper.or().in("parentId", parentIds);
        }
        return companiesMapper.selectCompanyInfo(queryWrapper);
    }

    /**
     * 根据 id 和 status 查询
     * 如果 id 为 null 则根据 status
     * 如果 status 为null则根据 id
     * 如果 id 和statsu 同为 null 则查询全部
     */
    public List<Companies> selectCompaniesByIdAndStatus(String id, Integer status) {
        return companiesMapper.selectCompaniesByIdAndStatus(id, status);
    }


    public List<Companies> selectAll() {
        return companiesMapper.selectList(null);
    }

    /**
     * 保存和更新
     */
    public boolean saveOrUpdate(Companies companies, User user) {
        companies.setUpdateTime(LocalDateTime.now());
        companies.setUpdateUser(user.getUserCode());
        if (StringUtil.notEmpty(companies.getSecondaryDomain())) {
            // 必须全部是小写
            companies.setSecondaryDomain(companies.getSecondaryDomain().toLowerCase());
        } else {
            companies.setSecondaryDomain(null);
        }
        if (StringUtil.notEmpty(companies.getId())) {
            companiesMapper.updateById(companies);
            return true;
        } else {
            companies.setParentId(user.getCompanyId());
            companies.setCreateTime(LocalDateTime.now());
            companies.setCreateUser(user.getUserCode());
            companiesMapper.insert(companies);
            return true;
        }
    }

    public boolean delete(String id) {
        List<Malls> malls = mallsService.list(new QueryWrapper<Malls>().lambda().eq(Malls::getCompanyId, id));
        if (malls != null && malls.size() > 0) {
            return false;
        } else {
            companiesMapper.deleteById(id);
            return true;
        }
    }

    /**
     * 根据 parentId 查出所有的 子id
     */
    public List<String> getTreeId(String parentId) {
        List<Companies> allCompanies = selectAll();
        List<Companies> companies = convertTree(allCompanies, parentId);
        List<String> result = convertTreeIds(companies, new HashSet<String>());
        return result;
    }

    public List<Companies> convertTree(List<Companies> companiesList, String parentId) {
        List<Companies> result = new ArrayList<>();
        if (companiesList != null && companiesList.size() > 0) {
            for (Companies c : companiesList) {
                if (c.getParentId() != null && (c.getParentId()).equals(parentId)) {
                    c.setChildren(convertTree(companiesList, c.getId()));
                    result.add(c);
                }
            }
        }
//        result.forEach(it -> {
//            if (it.getParentId() != null && it.getParentId().equals(parentId)) {
//                it.setChildren(convertTree(companiesList, it.getParentId()));
//                result.add(it);
//            }
//        });
        return result;
    }

    public List<String> convertTreeIds(List<Companies> companies, Set<String> result) {
        companies.forEach(it -> {
            result.add(it.getId());
            if (it.getChildren() != null) {
                convertTreeIds(it.getChildren(), result);
            }
        });
        return new ArrayList<>(result);
    }


}
